🧠C# Задача: структура, интерфейс и потеря состояния
Эта задача проверяет знание нюансов работы struct с интерфейсами. Поведение кажется очевидным — но только на первый взгляд.
📦 Задача
using System;
public interface ICounter { void Increment(); int Value { get; } }
public struct Counter : ICounter { private int _value; public void Increment() { _value++; }
public int Value => _value; }
class Program { static void Main() { ICounter counter = new Counter(); counter.Increment(); counter.Increment(); Console.WriteLine(counter.Value); } }
❓ Что выведет код?
A) 0
😎 1
C) 2
D) Ошибка компиляции
💡 Разбор Наивный ответ — 2, ведь Increment() вызывается дважды. Но!
📦 Counter — это struct, то есть value type. Когда мы присваиваем Counter переменной типа ICounter, происходит boxing — создаётся копия структуры в heap.
🔁 Каждый вызов counter.Increment() работает с новой копией, потому что интерфейс не может напрямую изменить struct без создания временного объекта.
🧱 В итоге Increment() изменяет внутреннее состояние временной копии, но не оригинального значения.
✅ Ответ: 0 🧨 Подвох Использование struct через интерфейс приводит к boxing.
Вызываемые методы действуют на копии, а не на оригинале.
Изменения теряются, и это не ошибка компиляции — это логическая ловушка.
🔧 Как исправить? Вариант 1: Сделать Counter классом:
```csharp public class Counter : ICounter { private int _value; public void Increment() => _value++; public int Value => _value; }
public class Counter : ICounter { private int _value; public void Increment() => _value++; public int Value => _value; }```
🧠C# Задача: структура, интерфейс и потеря состояния
Эта задача проверяет знание нюансов работы struct с интерфейсами. Поведение кажется очевидным — но только на первый взгляд.
📦 Задача
using System;
public interface ICounter { void Increment(); int Value { get; } }
public struct Counter : ICounter { private int _value; public void Increment() { _value++; }
public int Value => _value; }
class Program { static void Main() { ICounter counter = new Counter(); counter.Increment(); counter.Increment(); Console.WriteLine(counter.Value); } }
❓ Что выведет код?
A) 0
😎 1
C) 2
D) Ошибка компиляции
💡 Разбор Наивный ответ — 2, ведь Increment() вызывается дважды. Но!
📦 Counter — это struct, то есть value type. Когда мы присваиваем Counter переменной типа ICounter, происходит boxing — создаётся копия структуры в heap.
🔁 Каждый вызов counter.Increment() работает с новой копией, потому что интерфейс не может напрямую изменить struct без создания временного объекта.
🧱 В итоге Increment() изменяет внутреннее состояние временной копии, но не оригинального значения.
✅ Ответ: 0 🧨 Подвох Использование struct через интерфейс приводит к boxing.
Вызываемые методы действуют на копии, а не на оригинале.
Изменения теряются, и это не ошибка компиляции — это логическая ловушка.
🔧 Как исправить? Вариант 1: Сделать Counter классом:
```csharp public class Counter : ICounter { private int _value; public void Increment() => _value++; public int Value => _value; }
public class Counter : ICounter { private int _value; public void Increment() => _value++; public int Value => _value; }```
“To the extent it is used I fear it’s often for illicit finance. It’s an extremely inefficient way of conducting transactions, and the amount of energy that’s consumed in processing those transactions is staggering,” the former Fed chairwoman said. Yellen’s comments have been cited as a reason for bitcoin’s recent losses. However, Yellen’s assessment of bitcoin as a inefficient medium of exchange is an important point and one that has already been raised in the past by bitcoin bulls. Using a volatile asset in exchange for goods and services makes little sense if the asset can tumble 10% in a day, or surge 80% over the course of a two months as bitcoin has done in 2021, critics argue. To put a finer point on it, over the past 12 months bitcoin has registered 8 corrections, defined as a decline from a recent peak of at least 10% but not more than 20%, and two bear markets, which are defined as falls of 20% or more, according to Dow Jones Market Data.
Can I mute a Telegram group?
In recent times, Telegram has gained a lot of popularity because of the controversy over WhatsApp’s new privacy policy. In January 2021, Telegram was the most downloaded app worldwide and crossed 500 million monthly active users. And with so many active users on the app, people might get messages in bulk from a group or a channel that can be a little irritating. So to get rid of the same, you can mute groups, chats, and channels on Telegram just like WhatsApp. You can mute notifications for one hour, eight hours, or two days, or you can disable notifications forever.